/**
 * 微信API兼容性检查工具
 * 用于检查微信小程序API的可用性和版本兼容性
 */

/**
 * API版本要求
 */
export const API_VERSION_REQUIREMENTS = {
  // 基础API
  wx: { minVersion: '1.0.0', description: '微信小程序基础API' },
  wxLogin: { minVersion: '1.0.0', description: '微信登录API' },
  wxCheckSession: { minVersion: '1.0.0', description: '检查登录态API' },
  
  // 用户信息API
  wxGetUserInfo: { minVersion: '1.0.0', description: '获取用户信息API' },
  wxGetUserProfile: { minVersion: '2.10.4', description: '获取用户信息API（新版本）' },
  
  // 账号信息API
  wxGetAccountInfoSync: { minVersion: '2.2.2', description: '获取账号信息API' },
  
  // 插件相关API
  wxPluginLogin: { minVersion: '2.20.1', description: '插件登录API' },
  
  // 其他API
  wxGetSetting: { minVersion: '1.0.0', description: '获取设置API' },
  wxGetSystemInfoSync: { minVersion: '1.0.0', description: '获取系统信息API' }
}

/**
 * 微信API兼容性检查器
 */
class WechatApiChecker {
  constructor() {
    this.checkResults = {}
    this.systemInfo = null
    this.baseLibraryVersion = null
  }

  /**
   * 执行完整的API兼容性检查
   */
  async runFullCheck() {
    console.log('开始微信API兼容性检查...')
    
    this.checkResults = {}
    
    // 1. 检查环境
    await this.checkEnvironment()
    
    // 2. 检查基础库版本
    await this.checkBaseLibraryVersion()
    
    // 3. 检查API可用性
    await this.checkApiAvailability()
    
    // 4. 检查API版本兼容性
    await this.checkApiVersionCompatibility()
    
    // 5. 生成检查报告
    const report = this.generateCheckReport()
    
    console.log('微信API兼容性检查完成:', report)
    return report
  }

  /**
   * 检查运行环境
   */
  async checkEnvironment() {
    const result = {
      type: 'environment',
      status: 'info',
      title: '运行环境检查',
      details: {},
      message: ''
    }
    
    // 检查是否在微信小程序环境
    // #ifdef MP-WEIXIN
    result.status = 'success'
    result.message = '微信小程序环境'
    result.details = {
      platform: 'MP-WEIXIN',
      hasWx: typeof wx !== 'undefined'
    }
    // #endif
    
    // #ifndef MP-WEIXIN
    result.status = 'warning'
    result.message = '非微信小程序环境'
    result.details = {
      platform: 'OTHER',
      hasWx: typeof wx !== 'undefined'
    }
    // #endif
    
    this.checkResults.environment = result
  }

  /**
   * 检查基础库版本
   */
  async checkBaseLibraryVersion() {
    const result = {
      type: 'baseLibrary',
      status: 'info',
      title: '基础库版本检查',
      details: {},
      message: ''
    }
    
    try {
      if (typeof wx !== 'undefined' && typeof wx.getSystemInfoSync === 'function') {
        this.systemInfo = wx.getSystemInfoSync()
        this.baseLibraryVersion = this.systemInfo.version
        
        result.details = {
          version: this.baseLibraryVersion,
          platform: this.systemInfo.platform,
          system: this.systemInfo.system,
          SDKVersion: this.systemInfo.SDKVersion
        }
        
        // 检查基础库版本是否满足最低要求
        const minRequiredVersion = '2.0.0'
        if (this.compareVersion(this.baseLibraryVersion, minRequiredVersion) >= 0) {
          result.status = 'success'
          result.message = `基础库版本 ${this.baseLibraryVersion} 满足要求`
        } else {
          result.status = 'warning'
          result.message = `基础库版本 ${this.baseLibraryVersion} 较低，建议升级到 ${minRequiredVersion} 以上`
        }
      } else {
        result.status = 'error'
        result.message = '无法获取系统信息'
      }
    } catch (error) {
      result.status = 'error'
      result.message = `获取系统信息失败: ${error.message}`
      result.details = { error: error.message }
    }
    
    this.checkResults.baseLibrary = result
  }

  /**
   * 检查API可用性
   */
  async checkApiAvailability() {
    const result = {
      type: 'apiAvailability',
      status: 'info',
      title: 'API可用性检查',
      details: {},
      message: ''
    }
    
    const apiCheck = {}
    let availableCount = 0
    let totalCount = 0
    
    // 检查每个API的可用性
    for (const [apiName, requirement] of Object.entries(API_VERSION_REQUIREMENTS)) {
      totalCount++
      
      let isAvailable = false
      let error = null
      
      try {
        switch (apiName) {
          case 'wx':
            isAvailable = typeof wx !== 'undefined'
            break
          case 'wxLogin':
            isAvailable = typeof wx !== 'undefined' && typeof wx.login === 'function'
            break
          case 'wxCheckSession':
            isAvailable = typeof wx !== 'undefined' && typeof wx.checkSession === 'function'
            break
          case 'wxGetUserInfo':
            isAvailable = typeof wx !== 'undefined' && typeof wx.getUserInfo === 'function'
            break
          case 'wxGetUserProfile':
            isAvailable = typeof wx !== 'undefined' && typeof wx.getUserProfile === 'function'
            break
          case 'wxGetAccountInfoSync':
            isAvailable = typeof wx !== 'undefined' && typeof wx.getAccountInfoSync === 'function'
            break
          case 'wxPluginLogin':
            isAvailable = typeof wx !== 'undefined' && typeof wx.pluginLogin === 'function'
            break
          case 'wxGetSetting':
            isAvailable = typeof wx !== 'undefined' && typeof wx.getSetting === 'function'
            break
          case 'wxGetSystemInfoSync':
            isAvailable = typeof wx !== 'undefined' && typeof wx.getSystemInfoSync === 'function'
            break
          default:
            isAvailable = false
            error = '未知API'
        }
      } catch (err) {
        isAvailable = false
        error = err.message
      }
      
      apiCheck[apiName] = {
        available: isAvailable,
        error: error,
        requirement: requirement
      }
      
      if (isAvailable) {
        availableCount++
      }
    }
    
    result.details = {
      apiCheck,
      availableCount,
      totalCount,
      availabilityRate: Math.round((availableCount / totalCount) * 100)
    }
    
    if (availableCount === totalCount) {
      result.status = 'success'
      result.message = `所有API都可用 (${availableCount}/${totalCount})`
    } else if (availableCount > totalCount * 0.8) {
      result.status = 'warning'
      result.message = `大部分API可用 (${availableCount}/${totalCount})`
    } else {
      result.status = 'error'
      result.message = `多个API不可用 (${availableCount}/${totalCount})`
    }
    
    this.checkResults.apiAvailability = result
  }

  /**
   * 检查API版本兼容性
   */
  async checkApiVersionCompatibility() {
    const result = {
      type: 'apiVersionCompatibility',
      status: 'info',
      title: 'API版本兼容性检查',
      details: {},
      message: ''
    }
    
    if (!this.baseLibraryVersion) {
      result.status = 'error'
      result.message = '无法获取基础库版本信息'
      this.checkResults.apiVersionCompatibility = result
      return
    }
    
    const compatibilityCheck = {}
    let compatibleCount = 0
    let totalCount = 0
    
    for (const [apiName, requirement] of Object.entries(API_VERSION_REQUIREMENTS)) {
      totalCount++
      
      const isCompatible = this.compareVersion(this.baseLibraryVersion, requirement.minVersion) >= 0
      
      compatibilityCheck[apiName] = {
        compatible: isCompatible,
        currentVersion: this.baseLibraryVersion,
        requiredVersion: requirement.minVersion,
        description: requirement.description
      }
      
      if (isCompatible) {
        compatibleCount++
      }
    }
    
    result.details = {
      compatibilityCheck,
      compatibleCount,
      totalCount,
      compatibilityRate: Math.round((compatibleCount / totalCount) * 100)
    }
    
    if (compatibleCount === totalCount) {
      result.status = 'success'
      result.message = `所有API版本兼容 (${compatibleCount}/${totalCount})`
    } else if (compatibleCount > totalCount * 0.8) {
      result.status = 'warning'
      result.message = `大部分API版本兼容 (${compatibleCount}/${totalCount})`
    } else {
      result.status = 'error'
      result.message = `多个API版本不兼容 (${compatibleCount}/${totalCount})`
    }
    
    this.checkResults.apiVersionCompatibility = result
  }

  /**
   * 比较版本号
   * @param {string} version1 版本1
   * @param {string} version2 版本2
   * @returns {number} 比较结果：1表示version1>version2，0表示相等，-1表示version1<version2
   */
  compareVersion(version1, version2) {
    const v1Parts = version1.split('.').map(Number)
    const v2Parts = version2.split('.').map(Number)
    
    const maxLength = Math.max(v1Parts.length, v2Parts.length)
    
    for (let i = 0; i < maxLength; i++) {
      const v1 = v1Parts[i] || 0
      const v2 = v2Parts[i] || 0
      
      if (v1 > v2) return 1
      if (v1 < v2) return -1
    }
    
    return 0
  }

  /**
   * 生成检查报告
   */
  generateCheckReport() {
    const summary = {
      total: Object.keys(this.checkResults).length,
      success: 0,
      warning: 0,
      error: 0,
      info: 0,
      issues: [],
      recommendations: []
    }
    
    // 统计结果
    Object.values(this.checkResults).forEach(result => {
      summary[result.status]++
      
      if (result.status === 'error') {
        summary.issues.push({
          type: result.type,
          title: result.title,
          message: result.message
        })
      }
    })
    
    // 生成建议
    if (summary.error > 0) {
      summary.recommendations.push('请解决上述错误项以确保微信功能正常使用')
    }
    
    if (summary.warning > 0) {
      summary.recommendations.push('建议解决警告项以获得更好的用户体验')
    }
    
    // 特定建议
    const baseLibraryResult = this.checkResults.baseLibrary
    if (baseLibraryResult && baseLibraryResult.status === 'warning') {
      summary.recommendations.push('建议升级微信基础库版本以获得更好的API支持')
    }
    
    const apiAvailabilityResult = this.checkResults.apiAvailability
    if (apiAvailabilityResult && apiAvailabilityResult.details.availabilityRate < 80) {
      summary.recommendations.push('部分API不可用，请检查微信版本和权限设置')
    }
    
    return {
      summary,
      details: this.checkResults,
      timestamp: Date.now()
    }
  }

  /**
   * 获取特定API的检查结果
   */
  getApiCheckResult(apiName) {
    const availabilityResult = this.checkResults.apiAvailability
    const compatibilityResult = this.checkResults.apiVersionCompatibility
    
    if (!availabilityResult || !compatibilityResult) {
      return null
    }
    
    const availability = availabilityResult.details.apiCheck?.[apiName]
    const compatibility = compatibilityResult.details.compatibilityCheck?.[apiName]
    
    if (!availability || !compatibility) {
      return null
    }
    
    return {
      apiName,
      available: availability.available,
      compatible: compatibility.compatible,
      currentVersion: compatibility.currentVersion,
      requiredVersion: compatibility.requiredVersion,
      description: compatibility.description,
      error: availability.error
    }
  }

  /**
   * 检查特定API是否可用
   */
  isApiAvailable(apiName) {
    const result = this.getApiCheckResult(apiName)
    return result ? result.available && result.compatible : false
  }

  /**
   * 获取系统信息
   */
  getSystemInfo() {
    return this.systemInfo
  }

  /**
   * 获取基础库版本
   */
  getBaseLibraryVersion() {
    return this.baseLibraryVersion
  }
}

// 创建单例实例
const wechatApiChecker = new WechatApiChecker()

// 导出函数
export const runApiCheck = () => wechatApiChecker.runFullCheck()
export const getApiCheckResult = (apiName) => wechatApiChecker.getApiCheckResult(apiName)
export const isApiAvailable = (apiName) => wechatApiChecker.isApiAvailable(apiName)
export const getSystemInfo = () => wechatApiChecker.getSystemInfo()
export const getBaseLibraryVersion = () => wechatApiChecker.getBaseLibraryVersion()

export default wechatApiChecker 